package Text2;

import java.util.*;

public class Main {
    public static int N = 150010, n, m, idx;
    public static int[] h = new int[N];
    public static int[] e = new int[N];
    public static int[] ne = new int[N];
    public static int[] w = new int[N];
    public static int[] d = new int[N];
    public static boolean[] st = new boolean[N];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();
        Arrays.fill(h, -1);
        Arrays.fill(d, Integer.MAX_VALUE);
        d[1] = 0;
        for (int i = 0; i < m; i++) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            int c = scanner.nextInt();
            add(a, b, c);
        }
        System.out.println(dijkstra());
    }

    private static int dijkstra() {
        PriorityQueue<PII> p = new PriorityQueue<PII>();
        p.offer(new PII(0, 1));
        while (p.size() > 0) {
            PII t = p.poll();
            int distance = t.a, ver = t.b;
            if (!st[ver]) {
                st[ver]=true;
                for (int i = h[ver]; i != -1; i = ne[i]) {
                    int j = e[i];
                    if (d[j] > distance + w[i]) {
                        d[j] = distance + w[i];
                        p.offer(new PII(d[j],j));
                    }
                }
            }

        }
        if(d[n]==Integer.MAX_VALUE){
            return -1;
        }else {
            return d[n];
        }
    }
    private static void add(int a, int b, int c) {
        e[idx] = b;
        ne[idx] = h[a];
        w[idx] = c;
        h[a] = idx++;
    }
}
class PII implements Comparable<PII> {
    int a;//距离值
    int b;//点编号
    public PII(int a, int b) {
        this.a = a;
        this.b = b;
    }
    @Override
    public int compareTo(PII o) {
        return Integer.compare(a, o.a);
    }
}